package com.example.kangjujiaofei.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.kangjujiaofei.contants.ApiResponse;
import com.example.kangjujiaofei.contants.BankConfig;
import com.example.kangjujiaofei.contants.Contants;
import com.example.kangjujiaofei.entity.FaBill;
import com.example.kangjujiaofei.entity.FaBillPackage;
import com.example.kangjujiaofei.entity.FaUser;
import com.example.kangjujiaofei.entity.XSCReponseDataResponse;
import com.example.kangjujiaofei.entity.bill.BillRecord;
import com.example.kangjujiaofei.entity.home.HomeRecord;
import com.example.kangjujiaofei.utils.StringUtils;
import com.example.kangjujiaofei.utils.TokenViewUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class BunissesService {

    @Resource
    private XinShiChuanService shiChuanService;

    @Resource
    private TokenViewUtil tokenViewUtil;

    @Autowired
    private IFaBillService iFaBillService;

    @Autowired
    private IFaUserService userService;

    @Autowired
    private IFaBillPackageService faBillPackageService;


    @Value("${pinganpay.appId}")
    private String appid;


    @Value("${pinganpay.appid}")
    private String appId;


    @Value("${pinganpay.api_id}")
    private String api_id;


    @Value("${pinganpay.cusid}")
    private String cusid;

    @Value("${pinganpay.key}")
    private String key;

    //根据手机号，获取用户带缴费列表
    public ApiResponse getUserBill(String phone) throws ParseException {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String now = simpleDateFormat.format(date);
        List<Object> resultData = new ArrayList<>();
        for (String s : phone.split(",")) {
            //获取用户
            FaUser user = userService.getOne(new QueryWrapper<FaUser>().eq("phone", s));

            Map<String, Object> data = new HashMap<>();
            data.put("MobilePhone", s);
            data.put("MultiHouse", 1);
            String str = tokenViewUtil.getXinShiChuanData(2001, shiChuanService.getUUID(), shiChuanService.getNWExID(), data);
            XSCReponseDataResponse<List<HomeRecord>> dataResponse = JSON.parseObject(str, new TypeReference<XSCReponseDataResponse<List<HomeRecord>>>() {
            });
            data.put("CustomerType", 1);
            String straddress = tokenViewUtil.getXinShiChuanData(2001, shiChuanService.getUUID(), shiChuanService.getNWExID(), data);
            XSCReponseDataResponse<List<HomeRecord>> dataResponse121 = JSON.parseObject(straddress, new TypeReference<XSCReponseDataResponse<List<HomeRecord>>>() {
            });
            List<HomeRecord> list = new ArrayList<>();
            list.addAll( dataResponse.getResponse().getData().getRecord());
            list.addAll( dataResponse121.getResponse().getData().getRecord());
            //返回给前段展示数据
            //需要保存到数据中的数组
            List<FaBill> needAddList = new ArrayList<>();
            List<String> save = new ArrayList<>();
            List<Long> houseId = new ArrayList<>();
            for (HomeRecord homeRecord : list) {//循环获取待支付订单
                Map<String, List<BillRecord>> list_merge = new HashMap<>();

                Map<String, Object> home = new HashMap<>();
                home.put("HouseID", homeRecord.getHouseID());
                if(houseId.contains(homeRecord.getHouseID())){///去除重复查询房间信息
                    continue;
                }else{
                    houseId.add(homeRecord.getHouseID());
                }
                String addressName = homeRecord.getHouseName();
                String str1 = tokenViewUtil.getXinShiChuanData(5001, shiChuanService.getUUID(), shiChuanService.getNWExID(), home);
                XSCReponseDataResponse<List<BillRecord>> bills = JSON.parseObject(str1, new TypeReference<XSCReponseDataResponse<List<BillRecord>>>() {
                });
                if (bills.getResponse().getData().getRecord().size() > 0) {
                    aaa: for (BillRecord billRecord : bills.getResponse().getData().getRecord()) {
//                        addressName = billRecord.getUserAddress();

                        //处理fabill
                        //放到集合中返回前段方便展示
                        if (list_merge.get(billRecord.getChargeItemName()) == null) {
                            list_merge.put(billRecord.getChargeItemName(), new ArrayList<>());
                        }
                        FaBill faBill1 = iFaBillService.getOne(new QueryWrapper<FaBill>().eq("contract_no", billRecord.getContractNo()));
                        if (faBill1 == null) {
                            FaBill faBill = new FaBill();
                            if (user != null) {
                                faBill.setUserId(user.getId());
                            } else {
                                faBill.setUserId(0);
                            }
                            if(save.contains(billRecord.getContractNo())){
                                continue aaa;
                            }
                            save.add(billRecord.getContractNo());
                            faBill.setContractNo(billRecord.getContractNo());
                            faBill.setAddress(billRecord.getUserAddress());
                            faBill.setBiotopeNo(billRecord.getPreSaleNo());
                            faBill.setPayCircle(billRecord.getBillDate());
                            faBill.setAmount(billRecord.getBillAmount());
                            faBill.setState(0);
                            faBill.setAddTime(now);
                            needAddList.add(faBill);
                            list_merge.get(billRecord.getChargeItemName()).add(billRecord);
                        } else if (faBill1.getState() == 0) {
                            if(save.contains(billRecord.getContractNo())){
                                continue aaa;
                            }
                            save.add(billRecord.getContractNo());
                            if (!faBill1.getAmount().equals(billRecord.getBillAmount())) {
                                iFaBillService.removeById(faBill1);
                                FaBill faBill = new FaBill();
                                if (user != null) {
                                    faBill.setUserId(user.getId());
                                } else {
                                    faBill.setUserId(0);
                                }

                                faBill.setContractNo(billRecord.getContractNo());
                                faBill.setAddress(billRecord.getUserAddress());
                                faBill.setBiotopeNo(billRecord.getPreSaleNo());
                                faBill.setPayCircle(billRecord.getBillDate());
                                faBill.setAmount(billRecord.getBillAmount());
                                faBill.setState(0);
                                faBill.setAddTime(now);
                                needAddList.add(faBill);
                            }
                            list_merge.get(billRecord.getChargeItemName()).add(billRecord);
                        }

                    }
                }

                List<Object> itemList = new ArrayList<>();
                for (Map.Entry<String, List<BillRecord>> entry : list_merge.entrySet()) {
                    Map<String, Object> iiiii = new HashMap<>();
                    iiiii.put("type", entry.getKey());
                    iiiii.put("list", entry.getValue());
                    itemList.add(iiiii);
                }
                Map<String, Object> show_map = new HashMap<>();
                show_map.put("data", itemList);
                show_map.put("address", addressName);
                resultData.add(show_map);

            }
            iFaBillService.saveBatch(needAddList);
        }


        if (resultData.isEmpty()) {
            return ApiResponse.fail("null", "null");
        } else {
            return ApiResponse.success(resultData);
        }
    }


    //create预支付订单
    @Transactional
    public ApiResponse createPay(List<String> ContractNo) {
        List<FaBill> faBills = iFaBillService.list(new QueryWrapper<FaBill>().in("contract_no", ContractNo));
        if (faBills == null || faBills.size() == 0) {
            return ApiResponse.fail("fail", "fail");
        }
        Date date = new Date();
        SimpleDateFormat fabillTime = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = simpleDateFormat.format(date);
        String fabillPackageTime = fabillTime.format(date);
        FaBillPackage faBillPackage = new FaBillPackage();
        double d = Math.random();
        int b = (int) (d * 100000);
        faBillPackage.setType("微信物业支付");
        faBillPackage.setCellId(faBills.get(0).getBiotopeNo());
        faBillPackage.setAmount(new BigDecimal(faBills.get(0).getAmount()));
        faBillPackage.setPayCircle(faBills.get(0).getPayCircle());
        faBillPackage.setAddress(faBills.get(0).getAddress());
        faBillPackage.setContractNo(faBills.get(0).getContractNo());
        faBillPackage.setState(0);
        faBillPackage.setAddTime(now);
        faBillPackage.setUserId(faBills.get(0).getUserId());
        faBillPackage.setPackageId(appId + fabillPackageTime + b);
//        faBills1 = faBillPackageService.list(new QueryWrapper<FaBillPackage>().like("contract_no",faBills.get(0).getContractNo()));
        for (int i = 1; i < faBills.size(); i++) {
            BigDecimal decimal = faBillPackage.getAmount();
            faBillPackage.setAmount(decimal.add(new BigDecimal(faBills.get(i).getAmount())));
            faBillPackage.setContractNo(faBillPackage.getContractNo() + "," + faBills.get(i).getContractNo());
            faBillPackage.setPayCircle(faBillPackage.getPayCircle() + "," + faBills.get(i).getPayCircle());
        }

        faBillPackageService.save(faBillPackage);
        return ApiResponse.success(faBillPackage);
    }

    //生成支付链接
    public ApiResponse payBill(String packageId, String openid) throws Exception {
        FaBillPackage faBillPackage = faBillPackageService.getOne(new QueryWrapper<FaBillPackage>().eq("package_id", packageId).eq("state", 0));
        if (faBillPackage == null) {
            return ApiResponse.ERROR;
        }
        if (faBillPackage.getPayData() == null && faBillPackage.getShixiaoTime() == null) {
            String reserve1 = "KJWY00003";
            boolean isYongJia  = false;
            for (String key : BankConfig.YongjiaBankAccount.keySet()) {
                if (faBillPackage.getAddress().contains(key)){
                    reserve1 = BankConfig.YongjiaBankAccount.get(key);
                    isYongJia = true;
                }
            }
            if(!isYongJia){
                for (String key : BankConfig.BankAccount.keySet()) {
                    if (faBillPackage.getAddress().contains(key)){
                        reserve1 = BankConfig.BankAccount.get(key);
                    }
                }
            }

            String body = faBillPackage.getAddress();
            String body1 = reserve1 + "_" + body;
            String uuid = UUID.randomUUID().toString();
            String uuid2 = uuid.replaceAll("-", "");
            Date d = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

            Map<String, Object> param = new LinkedHashMap<>();
            param.put("app_id", appId);
            param.put("api_id", api_id);
            param.put("nonce_str", uuid2);
            param.put("timestamp", sdf.format(d));
            if(isYongJia){
                param.put("cusid", "m22080917241134031");
            }else {
                param.put("cusid", cusid);
            }

            param.put("paytype", Contants.PAY_WAY_WECHATPAY);
            param.put("paychnl", Contants.PAY_TYPE_PUBLICPAY);
            param.put("payway", Contants.PAY_CANAL_GENERAL_UNDERLINE);
            param.put("trxamt", faBillPackage.getAmount().multiply(new BigDecimal(100)).toBigInteger());//交易金额
//            param.put("trxamt", 1);//交易金额
            param.put("body", body1);
            param.put("validtime", 3);
            param.put("reqsn", packageId);//商户交易订单号
            param.put("notify_url", Contants.notify_url);
            param.put("sub_openid", openid);
            param.put("sub_appid", "wxdb701598ea97da51");
            param.put("reserve1", reserve1);
            String arrtoStr = StringUtils.getAsciiSort(param);//ASCII码从小到大排序=>字典序
            arrtoStr = arrtoStr + "key=" + key;//在stringA最后拼接上key得到stringSignTemp字符串
            String md5 = StringUtils.getMD5(arrtoStr, true, 32);//并对stringSignTemp进行MD5运算
            String sign = md5.toUpperCase();//再将得到的字符串所有字符转换为大写，得到sign值signValue
            param.put("sign", sign);
            String requestPostData = StringUtils.mapToXml(param);
            String reuslt = tokenViewUtil.httpPost(requestPostData, Contants.testUrl);
//            log.error(reuslt);
//            log.error("reqsn"+packageId);
            Map<String, String> result1 = StringUtils.xmlToMap(reuslt);
            faBillPackage.setPayData(result1.get("pay_data"));
            faBillPackage.setShixiaoTime((int) (new Date().getTime() + 800));
            faBillPackageService.updateById(faBillPackage);
            return ApiResponse.success(JSON.parseObject(result1.get("pay_data")));
//            return ApiResponse.success(JSON.toJSONString(faBillPackage));

        } else {
            return ApiResponse.success(JSON.parseObject(faBillPackage.getPayData()));
        }

    }



    @Transactional
    public ApiResponse onlyGetNeedPay(String houseId,String contantsNo) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String now = simpleDateFormat.format(date);
        List<Object> resultData = new ArrayList<>();
//        for (String s : phone.split(",")) {
            //获取用户
//            FaUser user = userService.getOne(new QueryWrapper<FaUser>().eq("phone", s));
//
//            Map<String, Object> data = new HashMap<>();
//            data.put("MobilePhone", s);
//            data.put("MultiHouse", 1);
//            String str = tokenViewUtil.getXinShiChuanData(2001, shiChuanService.getUUID(), shiChuanService.getNWExID(), data);
//            log.error(str);
//            XSCReponseDataResponse<List<HomeRecord>> dataResponse = JSON.parseObject(str, new TypeReference<XSCReponseDataResponse<List<HomeRecord>>>() {
//            });

            //返回给前段展示数据
            //需要保存到数据中的数组
            List<FaBill> needAddList = new ArrayList<>();
            for (String homeRecord : houseId.split(",")) {//循环获取待支付订单
                Map<String, List<BillRecord>> list_merge = new HashMap<>();

                Map<String, Object> home = new HashMap<>();
                home.put("HouseID", homeRecord);
//                String addressName = homeRecord.getHouseName();
                String str1 = tokenViewUtil.getXinShiChuanData(5001, shiChuanService.getUUID(), shiChuanService.getNWExID(), home);
                XSCReponseDataResponse<List<BillRecord>> bills = JSON.parseObject(str1, new TypeReference<XSCReponseDataResponse<List<BillRecord>>>() {
                });
                if (bills.getResponse().getData().getRecord().size() > 0) {
                    for (BillRecord billRecord : bills.getResponse().getData().getRecord()) {
//                        addressName = billRecord.getUserAddress();

                        //处理fabill
                        //放到集合中返回前段方便展示
                        if (list_merge.get(billRecord.getChargeItemName()) == null) {
                            list_merge.put(billRecord.getChargeItemName(), new ArrayList<>());
                        }
                        FaBill faBill1 = iFaBillService.getOne(new QueryWrapper<FaBill>().eq("contract_no", billRecord.getContractNo()));
                        if (faBill1 == null) {
                            FaBill faBill = new FaBill();
//                            if (user != null) {
//                                faBill.setUserId(user.getId());
//                            } else {
                                faBill.setUserId(0);
//                            }

                            faBill.setContractNo(billRecord.getContractNo());
                            faBill.setAddress(billRecord.getUserAddress());
                            faBill.setBiotopeNo(billRecord.getPreSaleNo());
                            faBill.setPayCircle(billRecord.getBillDate());
                            faBill.setAmount(billRecord.getBillAmount());
                            faBill.setState(0);
                            faBill.setAddTime(now);
                            needAddList.add(faBill);
                            for (String s : contantsNo.split(",")) {
                                if (s.equals(billRecord.getContractNo())){
                                    list_merge.get(billRecord.getChargeItemName()).add(billRecord);
                                }
                            }
                        } else if (faBill1.getState() == 0) {
                            if (!faBill1.getAmount().equals(billRecord.getBillAmount())) {
                                faBill1.setAmount(billRecord.getBillAmount());
                                needAddList.add(faBill1);
                            }
                            for (String s : contantsNo.split(",")) {
                                if (s.equals(billRecord.getContractNo())){
                                    list_merge.get(billRecord.getChargeItemName()).add(billRecord);
                                }
                            }
//                            list_merge.get(billRecord.getChargeItemName()).add(billRecord);
                        }

                    }
                }

                List<Object> itemList = new ArrayList<>();
                for (Map.Entry<String, List<BillRecord>> entry : list_merge.entrySet()) {
                    Map<String, Object> iiiii = new HashMap<>();
                    iiiii.put("type", entry.getKey());
                    iiiii.put("list", entry.getValue());
                    itemList.add(iiiii);
                }
                Map<String, Object> show_map = new HashMap<>();
                show_map.put("data", itemList);
                show_map.put("address", "地址");
                resultData.add(show_map);

            }
            iFaBillService.saveOrUpdateBatch(needAddList);
//        }


        if (resultData.isEmpty()) {
            return ApiResponse.fail("null", "null");
        } else {
            return ApiResponse.success(resultData);
        }
    }
}

